{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Pandas 数据替换",
        "",
        "本教程详细介绍如何使用 `replace()` 方法替换数据中的值。",
        "",
        "## 目录",
        "1. 基本替换",
        "2. 字典替换",
        "3. 正则表达式替换",
        "4. 多值替换",
        "5. 按列替换",
        "6. 高级技巧"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 导入库"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "import pandas as pd",
        "import numpy as np"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 1. 基本替换",
        "",
        "### 方法说明",
        "",
        "`replace()` 用于替换 DataFrame 或 Series 中的值。",
        "",
        "**语法:**",
        "```python",
        "df.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False)",
        "```",
        "",
        "**主要参数：**",
        "- `to_replace`: 要替换的值（标量、列表、字典、正则表达式）",
        "- `value`: 替换后的值",
        "- `inplace`: 是否在原 DataFrame 上修改",
        "- `limit`: 连续替换的最大数量",
        "- `regex`: 是否使用正则表达式",
        "",
        "**特点：**",
        "- ✅ 支持单个值、多个值替换",
        "- ✅ 支持字典映射",
        "- ✅ 支持正则表达式",
        "- ✅ 可以指定替换的列",
        "",
        "**适用场景：** 数据清洗，统一格式，修正错误"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例1: 创建示例数据"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "df = pd.DataFrame({",
        "    '姓名': ['张三', '李四', '王五', '赵六'],",
        "    '性别': ['男', '女', 'M', 'F'],  # 混合格式",
        "    '等级': ['A', 'B', 'C', 'D'],",
        "    '分数': [85, 90, 78, 65],",
        "    '状态': ['是', '否', 'yes', 'no']  # 中英文混合",
        "})",
        "",
        "print(\"原始 DataFrame:\")",
        "print(df)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例2: 单个值替换"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 替换单个值",
        "df_replaced = df.replace('M', '男')",
        "print(\"替换 'M' 为 '男':\")",
        "print(df_replaced)",
        "",
        "# 替换数值",
        "df_replaced = df.replace(85, 86)",
        "print(\"\\n替换数值 85 为 86:\")",
        "print(df_replaced)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例3: 多个值替换为同一个值"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 将多个值替换为同一个值",
        "df_replaced = df.replace(['M', 'F'], '男')  # M和F都替换为'男'",
        "print(\"将 'M' 和 'F' 都替换为 '男':\")",
        "print(df_replaced)",
        "",
        "# 多个数值替换",
        "df_replaced = df.replace([85, 90], 95)",
        "print(\"\\n将 85 和 90 都替换为 95:\")",
        "print(df_replaced)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例4: 使用 inplace 参数"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "df_copy = df.copy()",
        "df_copy.replace('M', '男', inplace=True)",
        "print(\"使用 inplace=True 直接修改:\")",
        "print(df_copy)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 2. 字典替换",
        "",
        "### 方法说明",
        "",
        "使用字典可以同时进行多个替换，格式更清晰。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例1: 简单字典替换"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 使用字典替换",
        "replace_dict = {",
        "    'M': '男',",
        "    'F': '女',",
        "    'yes': '是',",
        "    'no': '否'",
        "}",
        "",
        "df_replaced = df.replace(replace_dict)",
        "print(\"使用字典替换:\")",
        "print(df_replaced)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例2: 按列替换（字典中的字典）"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 为不同列指定不同的替换规则",
        "replace_dict = {",
        "    '性别': {'M': '男', 'F': '女'},",
        "    '状态': {'yes': '是', 'no': '否'}",
        "}",
        "",
        "df_replaced = df.replace(replace_dict)",
        "print(\"按列指定替换规则:\")",
        "print(df_replaced)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例3: 数值替换"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 数值替换",
        "df_num = pd.DataFrame({",
        "    '分数': [85, 90, 78, 65, 92],",
        "    '等级': ['A', 'B', 'C', 'D', 'A']",
        "})",
        "",
        "# 替换数值",
        "df_replaced = df_num.replace({85: 86, 90: 91})",
        "print(\"数值替换:\")",
        "print(df_replaced)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 3. 正则表达式替换",
        "",
        "### 方法说明",
        "",
        "使用正则表达式可以匹配模式进行替换。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例1: 基本正则替换"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "df_str = pd.DataFrame({",
        "    '文本': ['ABC123', 'DEF456', 'GHI789', 'JKL012']",
        "})",
        "",
        "print(\"原始数据:\")",
        "print(df_str)",
        "",
        "# 使用正则表达式替换数字",
        "df_replaced = df_str.replace(r'\\d+', 'XXX', regex=True)",
        "print(\"\\n使用正则表达式替换数字:\")",
        "print(df_replaced)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例2: 正则表达式模式替换"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "df_pattern = pd.DataFrame({",
        "    '电话': ['010-12345678', '021-87654321', '0755-11223344']",
        "})",
        "",
        "print(\"原始数据:\")",
        "print(df_pattern)",
        "",
        "# 替换电话号码中的-为空格",
        "df_replaced = df_pattern.replace(r'-', ' ', regex=True)",
        "print(\"\\n替换 '-' 为 ' ':\")",
        "print(df_replaced)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例3: 匹配开头或结尾"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "df_match = pd.DataFrame({",
        "    '文本': ['prefix_abc', 'prefix_def', 'suffix_ghi', 'suffix_jkl']",
        "})",
        "",
        "print(\"原始数据:\")",
        "print(df_match)",
        "",
        "# 替换以prefix_开头的",
        "df_replaced = df_match.replace(r'^prefix_', '开始_', regex=True)",
        "print(\"\\n替换以 'prefix_' 开头的:\")",
        "print(df_replaced)",
        "",
        "# 替换以suffix_开头的",
        "df_replaced = df_match.replace(r'^suffix_', '结束_', regex=True)",
        "print(\"\\n替换以 'suffix_' 开头的:\")",
        "print(df_replaced)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 4. 多值替换",
        "",
        "### 方法说明",
        "",
        "可以同时替换多个不同的值。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例1: 列表替换"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "df_multi = pd.DataFrame({",
        "    '值': ['A', 'B', 'C', 'D', 'A', 'B']",
        "})",
        "",
        "print(\"原始数据:\")",
        "print(df_multi)",
        "",
        "# 将A和B替换为X",
        "df_replaced = df_multi.replace(['A', 'B'], 'X')",
        "print(\"\\n将 'A' 和 'B' 替换为 'X':\")",
        "print(df_replaced)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例2: 多个值对应多个值"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "df_mapping = pd.DataFrame({",
        "    '等级': ['A', 'B', 'C', 'D', 'E']",
        "})",
        "",
        "print(\"原始数据:\")",
        "print(df_mapping)",
        "",
        "# 多个值对应多个值（列表顺序对应）",
        "df_replaced = df_mapping.replace(['A', 'B', 'C', 'D', 'E'], ",
        "                                  ['优秀', '良好', '中等', '及格', '不及格'])",
        "print(\"\\n映射替换:\")",
        "print(df_replaced)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 5. 按列替换",
        "",
        "### 方法说明",
        "",
        "可以为不同的列指定不同的替换规则。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例1: 只替换特定列"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "df_col = pd.DataFrame({",
        "    '列1': ['A', 'B', 'C'],",
        "    '列2': ['X', 'Y', 'Z'],",
        "    '列3': [1, 2, 3]",
        "})",
        "",
        "print(\"原始数据:\")",
        "print(df_col)",
        "",
        "# 只替换列1",
        "df_replaced = df_col.replace({'列1': {'A': '替换A', 'B': '替换B'}})",
        "print(\"\\n只替换 '列1':\")",
        "print(df_replaced)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例2: 不同列不同替换规则"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "df_different = pd.DataFrame({",
        "    '性别': ['M', 'F', 'M', 'F'],",
        "    '状态': ['yes', 'no', 'yes', 'no']",
        "})",
        "",
        "print(\"原始数据:\")",
        "print(df_different)",
        "",
        "# 不同列使用不同的替换规则",
        "replace_rules = {",
        "    '性别': {'M': '男', 'F': '女'},",
        "    '状态': {'yes': '是', 'no': '否'}",
        "}",
        "",
        "df_replaced = df_different.replace(replace_rules)",
        "print(\"\\n不同列不同替换规则:\")",
        "print(df_replaced)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 6. 高级技巧",
        "",
        "### 技巧1: 替换NaN值"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "df_nan = pd.DataFrame({",
        "    'A': [1, 2, np.nan, 4, 5],",
        "    'B': ['a', 'b', None, 'd', 'e']",
        "})",
        "",
        "print(\"原始数据（包含NaN）:\")",
        "print(df_nan)",
        "",
        "# 替换NaN",
        "df_replaced = df_nan.replace(np.nan, '缺失')",
        "print(\"\\n替换 NaN 为 '缺失':\")",
        "print(df_replaced)",
        "",
        "# 也可以使用fillna",
        "df_filled = df_nan.fillna('缺失')",
        "print(\"\\n使用 fillna 替换:\")",
        "print(df_filled)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 技巧2: 条件替换"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "df_conditional = pd.DataFrame({",
        "    '分数': [85, 90, 78, 65, 92],",
        "    '等级': ['A', 'B', 'C', 'D', 'A']",
        "})",
        "",
        "print(\"原始数据:\")",
        "print(df_conditional)",
        "",
        "# 分数小于80的替换为'不及格'",
        "df_replaced = df_conditional.replace(df_conditional[df_conditional['分数'] < 80]['等级'].values, ",
        "                                      '不及格')",
        "print(\"\\n分数小于80的等级替换为'不及格':\")",
        "print(df_replaced)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 技巧3: 链式替换"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "df_chain = pd.DataFrame({",
        "    '文本': ['abc123', 'def456', 'ghi789']",
        "})",
        "",
        "print(\"原始数据:\")",
        "print(df_chain)",
        "",
        "# 链式替换",
        "df_replaced = df_chain.replace(r'\\d+', 'NUM', regex=True).replace('abc', 'ABC')",
        "print(\"\\n链式替换:\")",
        "print(df_replaced)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 技巧4: 使用 limit 限制替换次数"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "df_limit = pd.DataFrame({",
        "    '值': ['A', 'A', 'A', 'B', 'B', 'B']",
        "})",
        "",
        "print(\"原始数据:\")",
        "print(df_limit)",
        "",
        "# 只替换前2个A",
        "df_replaced = df_limit.replace('A', 'X', limit=2)",
        "print(\"\\n只替换前2个 'A':\")",
        "print(df_replaced)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 总结",
        "",
        "### 方法对比",
        "",
        "| 方法 | 用途 | 优点 | 缺点 |",
        "|------|------|------|------|",
        "| `replace(标量)` | 单个值替换 | 简单 | 只能替换一个值 |",
        "| `replace(列表)` | 多个值替换 | 批量替换 | 只能替换为同一个值 |",
        "| `replace(字典)` | 映射替换 | 灵活清晰 | 需要定义字典 |",
        "| `replace(regex=True)` | 正则替换 | 模式匹配 | 需要正则表达式知识 |",
        "",
        "### 关键要点",
        "",
        "1. **基本替换**：使用 `replace(old, new)` 替换单个值",
        "2. **字典替换**：使用字典进行映射替换，更清晰",
        "3. **按列替换**：使用字典的字典为不同列指定不同规则",
        "4. **正则表达式**：使用 `regex=True` 进行模式匹配替换",
        "5. **链式替换**：可以连续调用多个 `replace()`",
        "6. **限制替换**：使用 `limit` 参数限制替换次数",
        "7. **替换NaN**：可以使用 `replace()` 或 `fillna()` 替换缺失值"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.8.0"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 4
}